<script lang="ts" setup>
import { ref } from 'vue'
import { getDocheckPhoneAPI, getDocheckCodeAPI, getDoFinishRegisterAPI, getDoSendMsgCodeAPI } from '@/API/register'
import { showToast } from 'vant'
import 'vant/es/toast/style'

import router from '@/router'

const tel = ref('')
const password = ref('')
const telcode = ref('')
const onSubmit = async () => {
  // 验证验证码
  await getDocheckCodeAPI(tel.value, telcode.value)

  const res2: any = await getDoFinishRegisterAPI(tel.value, password.value)
  if (res2.code == 200) {
    showToast(res2.message)
    setTimeout(() => {
      router.push('/login')
    }, 3000)
  }
}

//验证手机号正则
// const pattern = /^[1][3-9][0-9]{9}$/

//验证手机号是否被注册
const onChange = async () => {
  const res: any = await getDocheckPhoneAPI(tel.value)
  if (res.code != 200) showToast(res.message)
}

//获取验证码
const getCode = async () => {
  const res = await getDoSendMsgCodeAPI(tel.value)
  
  telcode.value = res.data
}

//返回上一级
const onClickLeft = () => history.back()
</script>

<template>
  <van-nav-bar class="navar" title="用户注册" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div class="top"></div>

  <van-form @submit="onSubmit">
    <van-cell-group inset style="padding-top: 32px">
      <van-field
        focus
        @change="onChange"
        v-model="tel"
        name="tel"
        label="手机号码"
        placeholder="手机号码"
        :rules="[
          { required: true, message: '请填写手机号码' }
          // { pattern, message: '手机号格式错误' }
        ]"
      />

      <div class="code">
        <van-field v-model="telcode" name="telcode" label="验证码" placeholder="验证码" :rules="[{ required: true, message: '请填写验证码' }]" />
        <van-button class="code1" type="success" @click="getCode">获取验证码</van-button>
      </div>
      <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 注册 </van-button>
    </div>
  </van-form>
  <van-button type="success" class="small" size="small" @click="router.push('/login')">去登录</van-button>
</template>

<style scoped lang="less">
.code {
  display: flex;
  justify-content: space-between;
  .code1 {
    width: 150px;
  }
}

.navar {
  background-color: gainsboro;
  color: #fff;
}

.top {
  width: 100%;
  height: 200px;
  background-color: pink;
  background: url('@/assets/猫.webp') no-repeat center center;
  background-size: 100% 100%;
}
</style>
